package com.jn.util.tag;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.BodyTagSupport;

import com.jn.util.CodeUtil;

public class DictCodeOptionTag extends BodyTagSupport {

	private static final long serialVersionUID = -7146553047338820754L;
	private String codeType;
	private String value;
	private String ignores;
	private String firstLabel;
	private String firstValue;

	public int doStartTag() throws JspException {
		StringBuffer html = new StringBuffer();
		html.append(getOptions());
		write(this.pageContext, html.toString());
		return SKIP_BODY;
	}

	@Override
	public void release() {
		super.release();
		this.codeType = null;
		this.value = null;
		this.ignores = null;
		this.firstLabel = null;
		this.firstValue = null;
	}

	private String getOptions() {
		StringBuffer optionBuffer = new StringBuffer();
		if (this.firstLabel != null && this.firstValue != null){
			optionBuffer.append("<option value=\"" + this.firstValue + "\">" + this.firstLabel + "</option>");
		}else if(this.firstLabel != null){
			optionBuffer.append("<option value=\"\">" + this.firstLabel + "</option>");
		}
		Map<String, String> map = CodeUtil.getCodeMap(this.codeType);

		List<String> ignoreList = new ArrayList<String>();
		if (this.ignores != null) {
			String[] arr = this.ignores.split(",");
			for (String s : arr) {
				ignoreList.add(s);
			}
		}
		for (String key : map.keySet()) {
			if (ignoreList.contains(key))
				continue;
			optionBuffer.append("<option value=\"").append(key).append("\"");
			if (value != null && this.value.equals(key)) {
				optionBuffer.append(" selected=\"selected\"");
			}
			optionBuffer.append(">").append((String) map.get(key)).append(
					"</option>");
		}
		return optionBuffer.toString();
	}

	public void write(PageContext context, String html) throws JspException {
		JspWriter writer = context.getOut();
		try {
			writer.print(html);
		} catch (IOException e) {
			e.printStackTrace();
			throw new JspException(e);
		}
	}

	public String getCodeType() {
		return codeType;
	}

	public void setCodeType(String codeType) {
		this.codeType = codeType;
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}

	public String getIgnores() {
		return ignores;
	}

	public void setIgnores(String ignores) {
		this.ignores = ignores;
	}

	public String getFirstLabel() {
		return firstLabel;
	}

	public void setFirstLabel(String firstLabel) {
		this.firstLabel = firstLabel;
	}

	public String getFirstValue() {
		return firstValue;
	}

	public void setFirstValue(String firstValue) {
		this.firstValue = firstValue;
	}

}
